package com.fox.infrastructure;

import com.fox.domain.model.Order;
import com.fox.domain.repository.OrderRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import java.util.UUID;

/**
 * JPA 实现的仓储
 * 将领域聚合与持久化实体（PO）映射，通过转换器装配
 */
@Repository
public class JpaOrderRepository implements OrderRepository {

    private final EntityManager em;
    private final OrderMapper orderMapper; // 将领域对象 ↔ 持久化 PO 转换

    public JpaOrderRepository(EntityManager em, OrderMapper orderMapper) {
        this.em = em;
        this.orderMapper = orderMapper;
    }

    @Override
    public void save(Order order) {
        OrderPO po = orderMapper.toPO(order);
        em.merge(po); // 如果 ID 存在则更新，否则插入
    }

    @Override
    public Optional<Order> findById(UUID id) {
        OrderPO po = em.find(OrderPO.class, id);
        if (po == null) {
            return Optional.empty();
        }
        return Optional.of(orderMapper.toDomain(po));
    }
}